import { sleep } from "@/utils";
import IpcParams from "../IpcParams";
import { createAgent } from './utils';
import Axios from 'axios';
import axiosRetry from 'axios-retry';
import TgwebParser from "./tgweb_parser";
const { io } = require("socket.io-client");

export default class SidekickGame {
  constructor(tokenInfo) {
    this.tokenInfo = tokenInfo
    const agent = createAgent(this.tokenInfo.proxy)
    const headers = {
      "Referer": "https://game.sidekick.fans/",
      "Content-Type": "application/json",
      "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_7_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148",
      "accept": "application/json, text/plain, */*",
      "sec-fetch-site": "same-site",
      "access-control-request-headers": "authorization",
      "sec-fetch-mode": "cors",
      "origin": "https://game.sidekick.fans",
      "sec-fetch-dest": "empty",
    }
    this.axios = Axios.create({
      headers: headers,
      httpAgent: agent,
      httpsAgent: agent,
      timeout: 90 * 1000,
    })
    axiosRetry(this.axios, {
      retries: 3, retryDelay: (retryCount) => {
        return 2000
      }
    });
  }

  async run() {
    try {
      this.tgwebParser = new TgwebParser(this.tokenInfo.tgweb)
      let tgwebUser = this.tgwebParser.getUser()
      const data = {
        "telegramId": tgwebUser.id,
        "firstName": tgwebUser.first_name,
        "lastName": tgwebUser.last_name,
        "languageCode": tgwebUser.language_code,
        "isVip": false,
        "init": this.tgwebParser.getSession(),
      }

      const loginRes = await this.axios.request("https://gameapi.sidekick.fans/api/user/login", {
        method: "post",
        data: data,
      })

      this.accessToken = loginRes.data.data.accessToken
      const userRes = await this.axios.request("https://gameapi.sidekick.fans/api/user/6162453001/date", {
        method: "get",
      })

      await this.setupSocket()

      const date = (new Date()).toLocaleString()
      this.tokenInfo.gameupdate = date
      this.tokenInfo.count = (this.tokenInfo.count || 0) + 1
      console.log(date, "sidekick end", this.tokenInfo.phone, "score: ", this.tokenInfo.score)
      return new IpcParams("runSidekick", this.tokenInfo)
    } catch (error) {
      console.log((new Date()).toLocaleString(), "sidekick error", this.tokenInfo.phone)
      if (error.response) {
        console.error(error.request.path, error.response)
      } else {
        console.error(error)
      }
      return new IpcParams("runSidekick", this.tokenInfo, error)
    }
  }
  async setupSocket() {
    return new Promise((resolve, reject) => {
      const serverURL = "https://gameapi.sidekick.fans"
      let agent = createAgent(this.tokenInfo.proxy)
      this.socket = io(serverURL, {
        transports: ["websocket"],
        autoConnect: false,
        auth: {
          token: "Bearer " + this.accessToken
        },
        agent: agent,
      })

      this.socket.on("connect", async () => {
        await this.runSocket()
      })
      this.socket.on("disconnect", () => {
        this.socket.disconnect()
        resolve()
      })

      this.socket.connect()

      const self = this
      setTimeout(() => {
        self.socket.disconnect()
      }, 10 * 1000);
    })
  }

  async runSocket() {
    this.socket.emit("streamerRanks", {}, (res) => {
      // console.log("streamerRanks", res)
    })
    this.socket.emit("getSeason2UserRank", {}, (res) => {
      // console.log("getSeason2UserRank", res)
    })
    this.socket.emit("getUserReward", {}, (res) => {
      // console.log("getUserReward", res)
      this.tokenInfo.score = res.diamond
    })
    this.socket.emit("getTaskList", {}, (res) => {
      // console.log("getTaskList", res)
      let taskIndex = Math.floor(Math.random() * res.length)
      let task = res[taskIndex]
      if (task.isFinish != true) {
        this.socket.emit("changeTask", {
          taskId: task._id
        }, (res) => {
          console.log("sidekick task", task._id, res)
        })
      }
    })
  }
}